package by.sjc.giz.web.controller;

import by.sjc.giz.model.Account;
import by.sjc.giz.model.Book;
import by.sjc.giz.security.CustomUserDetails;
import by.sjc.giz.service.AccountService;
import by.sjc.giz.service.BookService;
import by.sjc.giz.service.CustomerService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

/**
 * Created by irina on 02.08.14.
 */
@Controller
@RequestMapping("")
public class AccountController {

    public static final Logger logger = Logger.getLogger(AccountController.class);

    @Autowired
    AccountService accountService;
    @Autowired
    CustomerService customerService;
    @Autowired
    BookService bookService;

    @RequestMapping(value = {"", "/"})
    public String welcome() {
        return "redirect:/profile";
    }

    @PreAuthorize("isAnonymous()")
    @RequestMapping(value = {"/login"}, method = { RequestMethod.GET })
    public ModelAndView login(
            @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "message", required = false) String message) {

        ModelAndView mav = new ModelAndView();
        if (null != error)
            mav.addObject("error","Invalid username or password.");
        if (null != message)
            mav.addObject("message",message);

        mav.setViewName("login");
        return mav;
    }

    @PreAuthorize("isFullyAuthenticated()")
    @RequestMapping(value = {"/profile"})
    public ModelAndView profile(Authentication authentication) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("profile");
        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();

        float spentSum = accountService.getFundsSpentByAccount(account);
        mav.setViewName("profile");
        mav.addObject("account", account);
        mav.addObject("spentSum",spentSum);

        return mav;
    }


    @PreAuthorize("isAnonymous()")
    @RequestMapping(value = {"/registration"}, method = { RequestMethod.GET })
    public ModelAndView registration() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("account", new Account());
        mav.setViewName("registration");
        return mav;
    }


    @PreAuthorize("isAnonymous()")
    @RequestMapping(value = {"/registration"}, method = {RequestMethod.POST})
    public ModelAndView registration(
            @Valid Account inputAccount,
            BindingResult result) {

        ModelAndView mav = new ModelAndView();
        logger.info("register:" + inputAccount.toString());
        if (result.hasErrors()) {
            mav.setViewName("registration");
        } else {
            Account account = accountService.registerCustomerAccount(inputAccount);
            mav.setViewName("redirect:/login");
            mav.addObject("message","registration successful. You can log in now.");
        }

        return mav;
    }
    

	@PreAuthorize("isFullyAuthenticated()")
	@RequestMapping(value="/profile/favorites/add",method= { RequestMethod.POST })
    @ResponseBody
    public void addToFavorites(
    		@RequestParam int bookId, Authentication authentication) {
        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
    	Book book = bookService.getBookById(bookId);
    	customerService.addToFavorites(account, book);
    }

    @PreAuthorize("isFullyAuthenticated()")
	@RequestMapping(value="/profile/favorites/remove",method= { RequestMethod.POST })
    @ResponseBody
    public void removeFromFavorites(
    		@RequestParam int bookId, Authentication authentication) {
        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
    	Book book = bookService.getBookById(bookId);
    	customerService.removeFromFavorites(account, book);
    }

    @PreAuthorize("isFullyAuthenticated()")
    @RequestMapping(value = {"/profile/favorites"})
    public ModelAndView favorites(Authentication authentication) {
        ModelAndView mav = new ModelAndView();

        Account account = ((CustomUserDetails) authentication.getPrincipal()).getAccount();
        mav.setViewName("favorites");
        List<Book> books = customerService.getFavorites(account);
        mav.addObject("account", account);
        mav.addObject("books", books);
        return mav;
    }
}
